import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/live/live_detail_entity.dart';
import 'package:sports_new/utils/date_time_utils.dart';
import 'package:sports_new/widgets/card.dart';

import '../../../resources/colours.dart';
import '../../../utils/routes.dart';
import '../../../utils/utils.dart';
import '../../../widgets/base/qkd_image.dart';
import '../../../widgets/base/qkd_text.dart';
import '../../../widgets/gif.dart';
import '../../../widgets/loading/loading_widget.dart';

class LiveListView extends StatefulWidget {
  const LiveListView({super.key, required this.list, this.title, this.maxShow = 14}):isSliver = false;
  const LiveListView.sliver({super.key, required this.list, this.title, this.maxShow = 14}):isSliver = true;

  final String? title;
  final List<LiveDetailEntity>? list;
  final bool isSliver;
  final int maxShow;

  @override
  State<LiveListView> createState() => _LiveListViewState();
}

class _LiveListViewState extends State<LiveListView> {
  List<LiveDetailEntity> get list => widget.list??[];
  bool _hasMore = true;
  int get max => widget.maxShow;

  bool get hasMore => _hasMore;
  set hasMore(bool value) => setState(() => _hasMore = value);

  @override
  Widget build(BuildContext context) {
    Widget child = LoadingWidget<bool>(
        isLoading: false,
        data: list.isEmpty,
        noData: Container(),
        child: () => Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if(widget.title != null)
            QkdText(
              widget.title!,
              fontSize: 16, fontWeight: FontWeight.w500
            ).paddingOnly(top: 12,left: 12,right: 12),
            GridView.count(
              physics: const NeverScrollableScrollPhysics(),
              padding: EdgeInsets.fromLTRB(8,widget.title != null?12:8,8,0),
              shrinkWrap: true,
              crossAxisCount: 2,
              crossAxisSpacing: 8,
              mainAxisSpacing: 8,
              childAspectRatio: Get.width*175/375/151,
              children: List.generate(
                list.length,
                (index) => liveItem(list[index], index)
              ).sublist(
                0,hasMore && list.length > max?max:null
              ),
            ),
            if(list.length > max)
              showMore()
          ],
        )
    );
    return widget.isSliver?SliverToBoxAdapter(
      child: child,
    ):child;
  }

  Widget liveItem(LiveDetailEntity live,int index){
    String liveStatus = "未开始";
    Color tagColor = Colours.blue149CFF;
    if(live.status == 1){
      liveStatus = "直播中";
      tagColor = Colours.main;
    }else{
      if(live.publishTime.hasValue){
        var time = DateTime.parse(live.publishTime!);
        String hour = time.formatedString('HH:mm');
        if(time.isInToday()){
          liveStatus = "今天 $hour";
        }else {
          liveStatus = "${time.month}月${time.day}日 $hour";
        }
      }
      if(live.status == 2) tagColor = Colours.grey99;
    }
    return GestureDetector(
      onTap: () {
        if(live.status == 2){
          Utils.onEvent(
            "live_playback",params: {"id": live.liveId});
        }else{
          Utils.onEvent(
            "live_view",
            params: {
              "is_on": live.status == 1?1:0,
              "landscape": live.bindMatch == 1
            }
          );
        }
        if(live.bindMatch == 1) {
          Get.toNamed(
              live.sportsId == 1?Routes.zqMatchDetail:Routes.lqMatchDetail,
              arguments: live.matchId,
              parameters: {"roomId":"${live.liveId??""}"}
          );
        }else{
          Get.toNamed(
            Routes.liveNormal,
            arguments: live.liveId
          );
        }
      },
      child: Stack(
        children: [
          Block(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: CachedNetworkImage(
                    height: 100,
                    width: Get.width,
                    fit: BoxFit.cover,
                    imageUrl: live.image ?? ""
                  ),
                ),
                Container(height: 4),
                QkdText(
                  live.title ?? "",
                  maxLines: 1,
                  fontSize: 13,
                  fontWeight: FontWeight.w500,
                ).paddingSymmetric(horizontal: 8),
                Container(height: 4),
                DefaultTextStyle(
                  style: const TextStyle(fontSize: 12,color: Colours.grey99),
                  child: Row(
                    children: [
                      QkdImage(
                        imageUrl: live.expertLogo??"",
                        width: 18,height: 18,
                        shape: BoxShape.circle
                      ),
                      Container(width: 4),
                      Expanded(
                        child: QkdText(
                          live.expertName ?? "",
                          needCenter: true,
                          maxLines: 1,
                          fontSize: 12,
                        )
                      ),
                      Image.asset(Utils.getImgPath("live_hot.png"),width: 12,height: 12),
                      Container(width: 2),
                      QkdText("${live.hot ?? " "}",needCenter: true)
                    ]
                  ),
                ).paddingSymmetric(horizontal: 8),
                Container(height: 8)
              ]
            ),
          ),
          Positioned(
            right: 0,
            child: Container(
              height: 14,
              alignment: Alignment.center,
              padding: const EdgeInsets.symmetric(horizontal: 4),
              decoration: BoxDecoration(
                color: tagColor,
                borderRadius: BorderRadius.circular(3)
              ),
              child: Row(
                children: [
                  if(live.status == 1)
                    const GifWidget(
                      width: 10, height: 10,
                      asset: "in_live.gif",
                      duration: Duration(milliseconds: 500)
                    ).paddingSymmetric(vertical: 2),
                  QkdText(
                    liveStatus,
                    height: 1.4,
                    color: Colours.white,
                    fontSize: 10
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget showMore(){
    return Block(
      cardStyle: const CardStyle(
        height: 40,
        margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
      ),
      onTap: ()=> hasMore = !hasMore,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          QkdText(hasMore?"点击展开":"点击收起",
            fontSize: 12,color: Colours.grey99
          ),
          Container(width: 2),
          Image.asset(width: 16,
            Utils.getImgPath(
              hasMore?"arrow_down.png":"arrow_up.png"
            )
          )
        ],
      )
    );
  }
}
